<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background-image: url('@/assets/Yukimo.svg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: 10% center;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }

    .password-input-wrapper {
      position: relative;
      margin-bottom: 24px;
    }

    .password-toggle-icon {
      cursor: pointer;
      color: var(--el-text-color-placeholder);
      transition: color 0.2s;

      &:hover {
        color: var(--el-color-primary);
      }
    }

    .password-strength-meter {
      margin-top: 8px;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .strength-bar {
      height: 4px;
      border-radius: 2px;
      flex-grow: 1;
      background-color: var(--el-border-color-light);
      transition: all 0.3s;

      &.strength-0 {
        background-color: var(--el-color-error);
        width: 33%;
      }

      &.strength-1 {
        background-color: var(--el-color-warning);
        width: 66%;
      }

      &.strength-2 {
        background-color: var(--el-color-success);
        width: 100%;
      }
    }

    .strength-text {
      font-size: 12px;
      color: var(--el-text-color-secondary);

      .strength-0 & { color: var(--el-color-error); }
      .strength-1 & { color: var(--el-color-warning); }
      .strength-2 & { color: var(--el-color-success); }
    }
  }
}
</style>
<template>
  <el-row class="login-page" >
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 登录表单 -->
      <el-form ref="ruleFormRef" :model=registerData size="large" autocomplete="off" :rules="rules">
        <el-form-item>
          <h1 style="text-align: center;width:100%;">登录</h1>
        </el-form-item>
        <el-form-item prop="loginName">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password" class="password-input-wrapper">
          <el-input
              name="password"
              :prefix-icon="Lock"
              :type="showPassword ? 'text' : 'password'"
              placeholder="请输入密码（8-20位字母、数字和符号组合）"
              v-model.trim="registerData.password"
              @keyup.enter="login"
              show-password-toggle
              clearable
              :maxlength="20"
              :minlength="8"
          >
            <template #suffix>
              <el-icon
                  class="password-toggle-icon"
                  @click.stop="togglePasswordVisibility"
                  :title="showPassword ? '隐藏密码' : '显示密码'"
              >
                <component :is="showPassword ? Hide : View" />
              </el-icon>
            </template>
          </el-input>
          <div class="password-strength-meter" v-if="registerData.password">
            <div
                class="strength-bar"
                :class="getPasswordStrengthClass"
            ></div>
            <span class="strength-text">{{ passwordStrengthText }}</span>
          </div>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
             <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>
<script setup>
import {User, Lock, View, Hide} from '@element-plus/icons-vue'
import {ref, computed} from 'vue'
import { ElMessage } from 'element-plus'
//定义数据模型
const registerData = ref({
  username: '',
  password:'',
  rePassword: ''
})
const showPassword = ref(false)
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 密码强度计算
const passwordStrengthText = computed(() => {
  if (!registerData.value.password) return ''
  const strength = calculatePasswordStrength(registerData.value.password)
  return ['弱', '中', '强'][strength]
})

const getPasswordStrengthClass = computed(() => {
  if (!registerData.value.password) return ''
  const strength = calculatePasswordStrength(registerData.value.password)
  return [`strength-${strength}`]
})

const calculatePasswordStrength = (password) => {
  let strength = 0
  if (password.length >= 8) strength++
  if (/[A-Z]/.test(password)) strength++
  if (/[0-9]/.test(password)) strength++
  if (/[^A-Za-z0-9]/.test(password)) strength++
  return Math.min(2, Math.floor(strength / 2))
}
// 定义表单组件的引用
const ruleFormRef = ref(null)

//定义表单校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, 2: '长度为5~16位非空字符', trigger: 'blur' }
  ]
})

//绑定数据,复用注册表单的数据模型
//表单数据校验
//登录函数
import {userLoginService} from '@/api/user.js'
import {useTokenStore} from '@/stores/token.js'
import {useRouter} from 'vue-router'
const router = useRouter()
const tokenStore = useTokenStore();
const login = async () => {
  if (!ruleFormRef.value) return;

  try {
    // 1. 表单验证
    await ruleFormRef.value.validate();

    // 2. 调用登录接口
    const result = await userLoginService(registerData.value);
    console.log('完整响应:', result); // 调试用

    // 3. 明确检查业务状态码
    if (result.code !== 200) {
      throw new Error(result.message || '登录失败');
    }

    // 4. 验证Token格式
    if (!result.data || typeof result.data !== 'string') {
      throw new Error('无效的令牌格式');
    }

    // 5. 存储Token
    tokenStore.setToken(result.data);
    ElMessage.success('登录成功');

    // 6. 跳转页面
    await router.push('/index');

  } catch (error) {
    console.error('登录失败:', error);
    ElMessage.error(error.message || '登录异常');
  }
}
</script>